#include "chatclient.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QTextEdit>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QSpinBox>
#include <QComboBox>
#include <QMessageBox>
#include <QDateTime>
#include <QJsonDocument>
#include <QJsonObject>
#include <QApplication>
#include <QStyle>
#include <QKeyEvent>

ChatClient::ChatClient(QWidget *parent)
    : QWidget(parent)
    , udpSocket(nullptr)
    , database(new Database(this))
    , isConnected(false)
    , serverPort(8888)
    , currentTheme("default")
{
    // 初始化数据库
    if (!database->initDatabase()) {
        QMessageBox::warning(this, "警告", "数据库初始化失败！");
    }
    
    // 设置界面
    setupUI();
    
    // 设置窗口属性
    setWindowTitle("聊天客户端 - Qt网络聊天程序");
    setMinimumSize(500, 600);
    
    // 应用默认主题
    applyTheme("default");
}

ChatClient::~ChatClient()
{
    if (udpSocket) {
        udpSocket->close();
        delete udpSocket;
    }
}

void ChatClient::setupUI()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 创建标题
    QLabel *titleLabel = new QLabel("聊天客户端");
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 18px; color: #2c3e50; margin: 10px;");
    mainLayout->addWidget(titleLabel);
    
    // 创建连接设置面板
    QGridLayout *connectionLayout = new QGridLayout();
    
    QLabel *nameLabel = new QLabel("用户名:");
    nameEdit = new QLineEdit();
    nameEdit->setPlaceholderText("请输入用户名");
    nameEdit->setText("用户" + QString::number(qrand() % 1000));
    
    QLabel *serverLabel = new QLabel("服务器:");
    serverEdit = new QLineEdit();
    serverEdit->setPlaceholderText("服务器IP地址");
    serverEdit->setText("127.0.0.1");
    
    QLabel *portLabel = new QLabel("端口:");
    portSpinBox = new QSpinBox();
    portSpinBox->setRange(1024, 65535);
    portSpinBox->setValue(serverPort);
    portSpinBox->setFixedWidth(100);
    
    connectButton = new QPushButton("连接");
    disconnectButton = new QPushButton("断开");
    disconnectButton->setEnabled(false);
    
    connectionLayout->addWidget(nameLabel, 0, 0);
    connectionLayout->addWidget(nameEdit, 0, 1);
    connectionLayout->addWidget(serverLabel, 0, 2);
    connectionLayout->addWidget(serverEdit, 0, 3);
    connectionLayout->addWidget(portLabel, 1, 0);
    connectionLayout->addWidget(portSpinBox, 1, 1);
    connectionLayout->addWidget(connectButton, 1, 2);
    connectionLayout->addWidget(disconnectButton, 1, 3);
    
    mainLayout->addLayout(connectionLayout);
    
    // 创建状态显示
    statusLabel = new QLabel("状态: 未连接");
    statusLabel->setStyleSheet("color: #e74c3c; font-weight: bold;");
    mainLayout->addWidget(statusLabel);
    
    // 创建主题选择
    QHBoxLayout *themeLayout = new QHBoxLayout();
    QLabel *themeLabel = new QLabel("主题:");
    themeComboBox = new QComboBox();
    themeComboBox->addItems({"默认主题", "深色主题", "蓝色主题", "绿色主题"});
    themeButton = new QPushButton("应用主题");
    
    themeLayout->addWidget(themeLabel);
    themeLayout->addWidget(themeComboBox);
    themeLayout->addWidget(themeButton);
    themeLayout->addStretch();
    
    mainLayout->addLayout(themeLayout);
    
    // 创建聊天显示区域
    QLabel *chatLabel = new QLabel("聊天记录:");
    chatTextEdit = new QTextEdit();
    chatTextEdit->setReadOnly(true);
    chatTextEdit->setMinimumHeight(300);
    
    mainLayout->addWidget(chatLabel);
    mainLayout->addWidget(chatTextEdit);
    
    // 创建消息输入区域
    QHBoxLayout *inputLayout = new QHBoxLayout();
    
    messageEdit = new QLineEdit();
    messageEdit->setPlaceholderText("输入消息内容...");
    messageEdit->setMinimumHeight(30);
    
    sendButton = new QPushButton("发送");
    sendButton->setEnabled(false);
    
    inputLayout->addWidget(messageEdit);
    inputLayout->addWidget(sendButton);
    
    mainLayout->addLayout(inputLayout);
    
    // 创建功能按钮区域
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    
    historyButton = new QPushButton("历史记录");
    clearButton = new QPushButton("清空记录");
    
    buttonLayout->addWidget(historyButton);
    buttonLayout->addWidget(clearButton);
    buttonLayout->addStretch();
    
    mainLayout->addLayout(buttonLayout);
    
    // 连接信号和槽
    connect(connectButton, &QPushButton::clicked, this, &ChatClient::connectToServer);
    connect(disconnectButton, &QPushButton::clicked, this, &ChatClient::disconnectFromServer);
    connect(sendButton, &QPushButton::clicked, this, &ChatClient::sendMessage);
    connect(clearButton, &QPushButton::clicked, this, &ChatClient::clearHistory);
    connect(historyButton, &QPushButton::clicked, this, &ChatClient::loadHistory);
    connect(themeButton, &QPushButton::clicked, this, &ChatClient::switchTheme);
    connect(messageEdit, &QLineEdit::returnPressed, this, &ChatClient::handleReturnPressed);
}

void ChatClient::applyTheme(const QString &theme)
{
    QString styleSheet;
    
    if (theme == "dark") {
        styleSheet = R"(
            QWidget {
                background-color: #2c3e50;
                color: #ecf0f1;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
            }
            QTextEdit {
                background-color: #34495e;
                color: #ecf0f1;
                border: 1px solid #7f8c8d;
                border-radius: 5px;
                padding: 5px;
                font-size: 12px;
            }
            QLineEdit {
                background-color: #34495e;
                color: #ecf0f1;
                border: 1px solid #7f8c8d;
                border-radius: 3px;
                padding: 5px;
            }
            QPushButton {
                background-color: #3498db;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-size: 12px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QPushButton:pressed {
                background-color: #21618c;
            }
            QPushButton:disabled {
                background-color: #7f8c8d;
            }
            QLabel {
                color: #ecf0f1;
                font-weight: bold;
            }
            QSpinBox, QComboBox {
                background-color: #34495e;
                color: #ecf0f1;
                border: 1px solid #7f8c8d;
                border-radius: 3px;
                padding: 3px;
            }
        )";
    } else if (theme == "blue") {
        styleSheet = R"(
            QWidget {
                background-color: #e3f2fd;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
            }
            QTextEdit {
                background-color: white;
                border: 2px solid #2196f3;
                border-radius: 5px;
                padding: 5px;
                font-size: 12px;
            }
            QLineEdit {
                border: 2px solid #2196f3;
                border-radius: 3px;
                padding: 5px;
            }
            QPushButton {
                background-color: #2196f3;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-size: 12px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #1976d2;
            }
            QPushButton:pressed {
                background-color: #0d47a1;
            }
            QPushButton:disabled {
                background-color: #bdbdbd;
            }
            QLabel {
                color: #1565c0;
                font-weight: bold;
            }
            QSpinBox, QComboBox {
                border: 2px solid #2196f3;
                border-radius: 3px;
                padding: 3px;
            }
        )";
    } else if (theme == "green") {
        styleSheet = R"(
            QWidget {
                background-color: #e8f5e8;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
            }
            QTextEdit {
                background-color: white;
                border: 2px solid #4caf50;
                border-radius: 5px;
                padding: 5px;
                font-size: 12px;
            }
            QLineEdit {
                border: 2px solid #4caf50;
                border-radius: 3px;
                padding: 5px;
            }
            QPushButton {
                background-color: #4caf50;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-size: 12px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QPushButton:pressed {
                background-color: #3d8b40;
            }
            QPushButton:disabled {
                background-color: #cccccc;
            }
            QLabel {
                color: #2e7d32;
                font-weight: bold;
            }
            QSpinBox, QComboBox {
                border: 2px solid #4caf50;
                border-radius: 3px;
                padding: 3px;
            }
        )";
    } else {
        // 默认主题
        styleSheet = R"(
            QWidget {
                background-color: #f0f0f0;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
            }
            QTextEdit {
                background-color: white;
                border: 1px solid #ccc;
                border-radius: 5px;
                padding: 5px;
                font-size: 12px;
            }
            QLineEdit {
                border: 1px solid #ccc;
                border-radius: 3px;
                padding: 5px;
            }
            QPushButton {
                background-color: #4CAF50;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-size: 12px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QPushButton:pressed {
                background-color: #3d8b40;
            }
            QPushButton:disabled {
                background-color: #cccccc;
            }
            QLabel {
                color: #333;
                font-weight: bold;
            }
            QSpinBox, QComboBox {
                border: 1px solid #ccc;
                border-radius: 3px;
                padding: 3px;
            }
        )";
    }
    
    setStyleSheet(styleSheet);
    currentTheme = theme;
}

void ChatClient::connectToServer()
{
    if (isConnected) {
        return;
    }
    
    userName = nameEdit->text().trimmed();
    if (userName.isEmpty()) {
        QMessageBox::warning(this, "警告", "请输入用户名！");
        return;
    }
    
    serverAddress = QHostAddress(serverEdit->text().trimmed());
    if (serverAddress.isNull()) {
        QMessageBox::warning(this, "警告", "请输入有效的服务器地址！");
        return;
    }
    
    serverPort = portSpinBox->value();
    
    // 创建UDP套接字
    udpSocket = new QUdpSocket(this);
    
    // 绑定随机端口
    if (!udpSocket->bind()) {
        QMessageBox::critical(this, "错误", "无法绑定本地端口");
        return;
    }
    
    // 连接信号
    connect(udpSocket, &QUdpSocket::readyRead, this, &ChatClient::handleReadyRead);
    
    // 发送连接请求
    QJsonObject connectMsg;
    connectMsg["type"] = "connect";
    connectMsg["name"] = userName;
    
    QJsonDocument doc(connectMsg);
    udpSocket->writeDatagram(doc.toJson(), serverAddress, serverPort);
    
    isConnected = true;
    connectButton->setEnabled(false);
    disconnectButton->setEnabled(true);
    sendButton->setEnabled(true);
    nameEdit->setEnabled(false);
    serverEdit->setEnabled(false);
    portSpinBox->setEnabled(false);
    
    statusLabel->setText("状态: 已连接");
    statusLabel->setStyleSheet("color: #27ae60; font-weight: bold;");
    
    addChatMessage("系统: 已连接到服务器", false);
}

void ChatClient::disconnectFromServer()
{
    if (!isConnected) {
        return;
    }
    
    if (udpSocket) {
        udpSocket->close();
        delete udpSocket;
        udpSocket = nullptr;
    }
    
    isConnected = false;
    connectButton->setEnabled(true);
    disconnectButton->setEnabled(false);
    sendButton->setEnabled(false);
    nameEdit->setEnabled(true);
    serverEdit->setEnabled(true);
    portSpinBox->setEnabled(true);
    
    statusLabel->setText("状态: 已断开");
    statusLabel->setStyleSheet("color: #e74c3c; font-weight: bold;");
    
    addChatMessage("系统: 已断开连接", false);
}

void ChatClient::sendMessage()
{
    if (!isConnected) {
        return;
    }
    
    QString message = messageEdit->text().trimmed();
    if (message.isEmpty()) {
        return;
    }
    
    // 发送消息到服务器
    QJsonObject msgObj;
    msgObj["type"] = "message";
    msgObj["sender"] = userName;
    msgObj["message"] = message;
    
    QJsonDocument doc(msgObj);
    udpSocket->writeDatagram(doc.toJson(), serverAddress, serverPort);
    
    // 显示自己的消息
    addChatMessage(message, true);
    
    // 保存到本地数据库
    saveMessageLocally(message);
    
    // 清空输入框
    messageEdit->clear();
}

void ChatClient::handleReadyRead()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress senderAddr;
        quint16 senderPort;
        
        udpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddr, &senderPort);
        
        // 解析JSON消息
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(datagram, &error);
        
        if (error.error != QJsonParseError::NoError) {
            continue;
        }
        
        QJsonObject jsonObj = doc.object();
        QString type = jsonObj["type"].toString();
        
        if (type == "connect_ack") {
            QString message = jsonObj["message"].toString();
            addChatMessage("系统: " + message, false);
        } else if (type == "broadcast") {
            QString message = jsonObj["message"].toString();
            QString timestamp = jsonObj["timestamp"].toString();
            addChatMessage("[" + timestamp + "] " + message, false);
        }
    }
}

void ChatClient::clearHistory()
{
    if (database->clearHistory()) {
        chatTextEdit->clear();
        addChatMessage("系统: 聊天记录已清空", false);
    } else {
        addChatMessage("系统: 清空聊天记录失败", false);
    }
}

void ChatClient::loadHistory()
{
    QStringList history = database->loadHistory(30);
    chatTextEdit->clear();
    
    for (const QString &msg : history) {
        chatTextEdit->append(msg);
    }
    
    addChatMessage("系统: 已加载 " + QString::number(history.size()) + " 条历史记录", false);
}

void ChatClient::switchTheme()
{
    QString themeName = themeComboBox->currentText();
    QString theme;
    
    if (themeName == "深色主题") {
        theme = "dark";
    } else if (themeName == "蓝色主题") {
        theme = "blue";
    } else if (themeName == "绿色主题") {
        theme = "green";
    } else {
        theme = "default";
    }
    
    applyTheme(theme);
}

void ChatClient::handleReturnPressed()
{
    sendMessage();
}

void ChatClient::addChatMessage(const QString &message, bool isOwn)
{
    QString timestamp = getCurrentTimestamp();
    QString displayMsg;
    
    if (isOwn) {
        displayMsg = QString("[%1] 我: %2").arg(timestamp).arg(message);
        chatTextEdit->append("<span style='color: #2980b9; font-weight: bold;'>" + displayMsg + "</span>");
    } else {
        displayMsg = QString("[%1] %2").arg(timestamp).arg(message);
        chatTextEdit->append(displayMsg);
    }
    
    // 滚动到底部
    QTextCursor cursor = chatTextEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    chatTextEdit->setTextCursor(cursor);
}

QString ChatClient::getCurrentTimestamp()
{
    return QDateTime::currentDateTime().toString("hh:mm:ss");
}

void ChatClient::saveMessageLocally(const QString &message)
{
    QString timestamp = getCurrentTimestamp();
    database->saveMessage(userName, message, timestamp);
}
